package com.renwei.yunlong.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.renwei.yunlong.R;
import com.renwei.yunlong.adapter.ServerListAdapter;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.ServerInfo;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.UtilList;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import org.litepal.crud.DataSupport;
import org.litepal.crud.async.UpdateOrDeleteExecutor;
import org.litepal.crud.callback.UpdateOrDeleteCallback;

import java.util.List;

/**
 * Project :  yunna.
 * Package name: com.renwei.yunlong.activity
 * Created by :  Benjamin.
 * Created time: 2018/3/15 9:33
 * Changed by :  Benjamin.
 * Changed time: 2018/3/15 9:33
 * Class description:
 */

public class ServerListActivity extends BaseActivity implements View.OnClickListener, ServerListAdapter.ClickListenter, OnRefreshListener {

    private XRecyclerView configList;
    private SmartRefreshLayout smtRefresh;
    private TextView ivBack;
    private TextView tvTitle;
    private TextView tvRight;
    private ServerListAdapter listAdapter;
    private RelativeLayout serverAdd;

    public static void openActivity(Context context) {
        context.startActivity(new Intent(context, ServerListActivity.class));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        setContentView(R.layout.activity_server_list);
        initView();
    }

    private void initView() {
        configList = findViewById(R.id.config_list);
        smtRefresh = findViewById(R.id.smt_refresh);
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        tvTitle = findViewById(R.id.tv_title);
        tvRight = findViewById(R.id.tv_right);
        tvRight.setOnClickListener(this);
        smtRefresh = findViewById(R.id.smt_refresh);
        View view = LayoutInflater.from(this).inflate(R.layout.layout_server_add, null);
        serverAdd = view.findViewById(R.id.server_add);
        serverAdd.setOnClickListener(this);
        tvTitle.setText("网络设置");
        tvRight.setText("管理");
        configList.setLayoutManager(new LinearLayoutManager(this));
        listAdapter = new ServerListAdapter(this);
        listAdapter.setClickListenter(this);
        smtRefresh.setOnRefreshListener(this);
        configList.setAdapter(listAdapter);
        configList.setFootView(view);
    }

    @Override
    protected void onResume() {
        super.onResume();
        smtRefresh.autoRefresh();

    }

    private void initData() {
        List<ServerInfo> serverInfoList = DataSupport.findAll(ServerInfo.class);
        listAdapter.refresh(serverInfoList, false);
        smtRefresh.finishRefresh();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.iv_back:
                this.finish();
                break;
            case R.id.tv_right:
                //管理
                /*if (listAdapter != null) {
                    if ("管理".equals(tvRight.getText().toString())) {
                        ServerListActivity.openActivity(true);
                    } else {
                        listAdapter.openTab(false);
                    }
                }*/
                ServerListOpenActivity.openActivity(this);
                break;
            case R.id.server_add:
                ServerEditActivity.openActivity(this, "");
                break;
        }
    }

    @Override
    public void onSelected(ServerInfo info) {
        ServerInfo serverInfo = new ServerInfo();
        serverInfo.setCurrent("0");
        serverInfo.updateAll("current=?", "1");
        info.setCurrent("1");
        info.saveOrUpdate("serverName=?", info.getServerName());
        smtRefresh.autoRefresh();
        // 延迟15秒
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // do something
                ServerListActivity.this.finish();
            }

        }, 1 * 1000);
    }

    @Override
    public void onEdit(ServerInfo info) {
        ServerEditActivity.openActivity(this, info.getServerName());

    }

    @Override
    public void onDelete(ServerInfo info) {
        UpdateOrDeleteExecutor callback = DataSupport.deleteAllAsync(ServerInfo.class, "serverName = ?", info.getServerName());
        callback.listen(new UpdateOrDeleteCallback() {
            @Override
            public void onFinish(int rowsAffected) {
                //判断数据库中是否有当前选中列  ，如果有就刷新，没有就取出所有数据的第一行设置默认
                int count = DataSupport.where("current = ?", "1").count(ServerInfo.class);
                if (count == 0) {
                    List<ServerInfo> currentList = DataSupport.findAll(ServerInfo.class);
                    if (UtilList.getCount(currentList) == 1) {
                        ServerInfo serverInfo = currentList.get(0);
                        serverInfo.setCurrent("1");
                        serverInfo.saveOrUpdate("serverName = ?", serverInfo.getServerName());
                    }
                }
                smtRefresh.autoRefresh();
            }
        });
    }


    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        initData();
    }
}

